﻿// /****************************************************************************************************************************
//  * 项目名称： 
//  * 类 名 称：AuxiliaryMaterialApplyService
//  * 功能说明：
//  * 版    本：0.0.1
//  * 作    者：史垚祎
//  * 邮    箱：396038130@qq.com
//  * 创建时间：2024/5/15 15:54
//  * 更新人：
//  * 更新时间：
//  * 更新说明：
// /****************************************************************************************************************************/
//
using System;
using NP.BPMReportPlatform.AuxiliaryMaterial.Dto;
using System.Collections.Generic;
using System.Threading.Tasks;
using NP.BPMReportPlatform.Finance;
using NP.BPMReportPlatform.Finance.Dto;
using Volo.Abp.Application.Dtos;
using SqlSugar;
using NP.BPMReportPlatform.BPMPlatform;
using NP.BPMReportPlatform.Utils;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.BPM_Business;
using NP.BPMReportPlatform.Entities.BPM_Platform;
using System.Linq;

namespace NP.BPMReportPlatform.AuxiliaryMaterial
{
    public class AuxiliaryMaterialApplyService : BPMReportPlatformAppService, IAuxiliaryMaterialApplyService
    {
        readonly SqlSugarClient _db;
        readonly SqlSugarClient _dbPlatform;
        readonly IBPMUtilsAppService _bPMUtilsApp;
        readonly IBPMPlatformAppService _iBPMPlatformApp;
        public AuxiliaryMaterialApplyService(ISqlSugarAppService sqlSugarAppService,
            IBPMUtilsAppService bPMUtilsApp, IBPMPlatformAppService iBPMPlatformApp)
        {
            _db = sqlSugarAppService.GetBusinessInstance();
            _dbPlatform = sqlSugarAppService.GetPlatformInstance();
            _bPMUtilsApp = bPMUtilsApp;
            _iBPMPlatformApp = iBPMPlatformApp;
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<PagedResultDto<AuxiliaryMaterialApplyOutput>> GetAllAsync(GetAuxiliaryMaterialApplyInput input)
        {
            RefAsync<int> totalCount = 0;

            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToPageListAsync(input.PageIndex, input.PageSize, totalCount);

            var userId = await _iBPMPlatformApp.GetUserAsync(CurrentUser.UserName);

            listViewDto.ForEach(x => x.Url = _bPMUtilsApp.GetProcessUrl(x.InstanceId, userId));
            SetRequirementTypeName(listViewDto);
            return new PagedResultDto<AuxiliaryMaterialApplyOutput>()
            {
                TotalCount = totalCount,
                Items = listViewDto
            };
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<List<AuxiliaryMaterialApplyOutput>> ExportAsync(GetAuxiliaryMaterialApplyInput input)
        {
            var listQueryable = GetQueryable(input);
            var listViewDto = await listQueryable.ToListAsync();
            SetRequirementTypeName(listViewDto);
            return listViewDto;
        }

        void SetRequirementTypeName(List<AuxiliaryMaterialApplyOutput> list)
        {
            if (list == null) return;
            list.ForEach(item =>
            {
                var nameList = new List<string>();
                if (item.RequirementType1)
                {
                    nameList.Add("新品开发");
                }
                if (item.RequirementType2)
                {
                    nameList.Add("二供开发");
                }
                if (item.RequirementType3)
                {
                    nameList.Add("成本精进");
                }
                if (item.RequirementType4)
                {
                    nameList.Add("品质改善");
                }
                if (item.RequirementType5)
                {
                    nameList.Add("飞检");
                }
                if (item.RequirementType6)
                {
                    nameList.Add("小试");
                }
                if (item.RequirementType7)
                {
                    nameList.Add("可行性分析");
                }
                if (item.RequirementType8)
                {
                    nameList.Add("投诉分析");
                }
                if (item.RequirementType9)
                {
                    nameList.Add("其他");
                }
                item.RequirementTypeName = string.Join(",", nameList);

                // 状态,0发起,1完成,2拒绝,3退回,4撤回
                switch (item.Status)
                {
                    case 0:
                        item.StatusName = "发起";
                        break;
                    case 1:
                        item.StatusName = "完成";
                        break;
                    case 2:
                        item.StatusName = "拒绝";
                        break;
                    case 3:
                        item.StatusName = "退回";
                        break;
                    case 4:
                        item.StatusName = "撤回";
                        break;
                    default:
                        item.StatusName = "-";
                        break;
                }

            });
        }


        private ISugarQueryable<AuxiliaryMaterialApplyOutput> GetQueryable(GetAuxiliaryMaterialApplyInput input)
        {
            var SubmitDateEnd = DateTime.Now;
            var SubmitDateStrat = DateTime.Now;

            if (input.StartDate.HasValue)
            {
                SubmitDateStrat = input.StartDate.Value;
            }
            if (input.EndDate.HasValue)
            {
                SubmitDateEnd = input.EndDate.Value.AddDays(1);
            }
            var noList = new List<string>();
            if (!string.IsNullOrEmpty(input.InstanceId))
            {
                noList = input.InstanceId.Split(new char[] { ',', ' ', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            }


            var uQuery = _dbPlatform.Queryable<Users>()
                .WhereIF(!string.IsNullOrEmpty(input.UserName), x => x.UserName.Contains(input.UserName) || x.WorkNumber == input.UserName).AS("BPM_Platform.Users");
            var pQuery = _db.Queryable<BusinessProcessesNew>()
                .WhereIF(input.StartDate.HasValue, x => x.StartTime >= SubmitDateStrat && x.StartTime < SubmitDateEnd);

            var tQuery = _db.Queryable<AuxiliaryMaterialApply>()
                .WhereIF(!string.IsNullOrEmpty(input.InstanceId), x => noList.Contains(x.InstanceNumber))
                .WhereIF(!string.IsNullOrEmpty(input.Dept), x => x.Dept.Contains(input.Dept))
                .WhereIF(!string.IsNullOrEmpty(input.SupplierName), x => x.SupplierName.Contains(input.SupplierName));


            var query = pQuery.InnerJoin(uQuery, (p, u) => p.StartUserId == u.UserId)
                    .InnerJoin(tQuery, (p, u, t) => p.InstanceId == t.InstanceNumber)
                    .Select((p, u, t) => new AuxiliaryMaterialApplyOutput()
                    {
                        InstanceId = p.InstanceId,
                        CreateDate = p.StartTime,
                        StartUserName = p.StartUserName,
                        Dept = t.Dept,
                        SampleDeliveryDate = t.SampleDeliveryDate,
                        SampleName = t.SampleName,
                        SupplierName = t.SupplierName,
                        YearOutputAmount = t.YearOutputAmount,
                        SupplierCode = t.SupplierCode,
                        FinishDate = t.FinishDate,
                        ProjectSource = t.ProjectSource,
                        RequirementType1 = t.RequirementType1,
                        RequirementType2 = t.RequirementType2,
                        RequirementType3 = t.RequirementType3,
                        RequirementType4 = t.RequirementType4,
                        RequirementType5 = t.RequirementType5,
                        RequirementType6 = t.RequirementType6,
                        RequirementType7 = t.RequirementType7,
                        RequirementType8 = t.RequirementType8,
                        RequirementType9 = t.RequirementType9,
                        SampleCount = t.SampleCount,
                        SendDept = t.SendDept
                    }).OrderBy(p => p.InstanceId, OrderByType.Desc);


            return query;
        }

    }
}

